import { cartList, addCart } from "@/common/apis/cart";
import { delCart } from "../common/apis/cart";
import store from "../store";

export default {
  state() {
    return {
      list: [],
      checkCart: {},
    };
  },

  getters: {
    // 产品在购物车的数量
    getInCartCount(state) {
      return (id) => {
        const current = state.list.find((i) => i.variant.id == id);
        if (current) {
          return current.quantity;
        }
        return "";
      };
    },
    // 获取产品所有变体在购物车中的数量
    getInCartCountAll(state) {
      return (id) => {
        console.log(id);
        let count = 0;
        state.list
          .filter((i) => i.product.id == id)
          .forEach((i) => {
            count += i.quantity;
          });
        return count;
      };
    },
  },

  mutations: {
    changeList(state, data) {
      state.list = data;
      const tabbar = JSON.parse(JSON.stringify(store.state.user.tabbar));
      tabbar[3].badge = data.length;
      store.commit("SET_TABBAR", tabbar);
    },
    // 是否购物车数据检测
    getCheckCart(state, list) {
      console.log(list);
      let obj = {};
      list.map((item) => {
        if (obj[item.variant.id]) {
          obj[item.variant.id + ""] = {
            num: item.quantity + obj[item.variant.id + ""].num,
            cartOrderId: item.id,
          };
        } else {
          obj[item.variant.id + ""] = {
            num: item.quantity,
            cartOrderId: item.id,
          };
        }
      });
      state.checkCart = obj;
    },
  },

  actions: {
    // 购物车列表
    async fetchCartList({ commit }) {
      const response = await cartList();
      if (response) {
        commit("changeList", response);
        commit("getCheckCart", response);
      }
      return response;
    },
    // 添加购物车
    async fetchAddCart({ state, dispatch }, data) {
      const response = await addCart(data);
      if (response) {
        // 如果该商品不存在购物车则刷新列表
        if (!state.list.some((i) => i.variant.id == data.variant_id)) {
          await dispatch("fetchCartList");
        }
      }
      return response;
    },
    // 删除购物车
    async fetchDelCart({ state, commit }, id) {
      const response = await delCart(id);
      const index = state.list.findIndex((i) => i.id == id);
      console.log(index);
      if (index != -1) {
        state.list.splice(index, 1);
        commit("changeList", state.list);
        commit("getCheckCart", state.list);
      }
      return response;
    },
  },
};
